package com.android.nextBus.Activities;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.nextBus.Activities.ViewTimesActivity.PointOverlay;
import com.android.nextBus.DB.MapItem;
import com.android.nextBus.DB.SQLiteOperationsWrapper;
import com.android.nextBus.JSON.BaseServicesURL;
import com.android.nextBus.JSON.JSONBusStopHTTPGet;
import com.android.nextBus.JSON.ShapeParser;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;

public class ViewRouteMapActivity extends MapActivity {

	private int shapeID;
	private String tripName;
	private List<Overlay> mapOverlays;
	private Projection projection;
	private SQLiteOperationsWrapper db;
	private MapItem aMapItem;
	private PointOverlay myPointOverlay;
	private GeoPoint stopPoint;
	private  ProgressBar progess ; 
	private TextView txtLoading ;
	private MapView map;
	private Context ct;
	private GeoPoint center;
	private RelativeLayout rl;
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.route_map);
		ct = this;
		progess = (ProgressBar) findViewById(R.id.ProgressBar); 
		txtLoading = (TextView) findViewById(R.id.loading);
		
		progess.setVisibility(View.VISIBLE);  
		txtLoading.setVisibility(View.VISIBLE);  
		rl = (RelativeLayout)findViewById(R.id.myContainer2);
		
		// MapView object that holds the map
		 map = (MapView) findViewById(R.id.map);
		
		// set the zoom of the map
		map.getController().setZoom(13);
		
		// show the zoom controls for the MapView
		map.setBuiltInZoomControls(true);
		
		
		Drawable drawable = this.getResources().getDrawable(R.drawable.next_bus_pin_small);
        myPointOverlay =  
                new PointOverlay(drawable, this);
		
        stopPoint  = new GeoPoint((int) (getIntent().getExtras().getInt(ViewTimesActivity.STOP_LAT_KEY)),
					(int) (getIntent().getExtras().getInt(ViewTimesActivity.STOP_LON_KEY)));
        
		OverlayItem overlayitem =   
                new OverlayItem(stopPoint, "Hello", "!"); 
		
   
        myPointOverlay.addOverlay(overlayitem);
		
		// add overlays to the map
		mapOverlays = map.getOverlays();
		projection = map.getProjection();
		mapOverlays.add(myPointOverlay);
		
		
		// TextView holding the name of the trip the map is displaying
		final TextView mapHeader = (TextView) findViewById(R.id.map_header);
		
		tripName = getIntent().getStringExtra(ViewTimesActivity.TRIP_NAME_KEY);
		//String routeName = getIntent().getStringExtra(ViewRoutesActivity.ROUTE_NAME_KEY);
		shapeID = getIntent().getIntExtra(ViewTimesActivity.SHAPE_ID_KEY, -1);
	
		// Set the text for the Map header.
		mapHeader.setText(tripName);
		
		start();
		
		
		
	}
	
	
	class PointOverlay extends ItemizedOverlay<OverlayItem> {
		
		   private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
		   
		   private Context context;
		   
		   public PointOverlay(Drawable defaultMarker) {
		        super(boundCenterBottom(defaultMarker));
		   }
		   
		   public PointOverlay(Drawable defaultMarker, Context context) {
		        this(defaultMarker);
		        this.context = context;
		   }

		   @Override
		   protected OverlayItem createItem(int i) {
		      return mapOverlays.get(i);
		   }

		   @Override
		   public int size() {
		      return mapOverlays.size();
		   }
		   
		   @Override
		   protected boolean onTap(int index) {
			   /*
		      OverlayItem item = mapOverlays.get(index);
		      AlertDialog.Builder dialog = new AlertDialog.Builder(context);
		      dialog.setTitle(item.getTitle());
		      dialog.setMessage(item.getSnippet());
		      dialog.show();
		      */
		      return true;
		   }
		   
		   public void addOverlay(OverlayItem overlay) {
		      mapOverlays.add(overlay);
		       this.populate();
		   }


	}
	
	
	
	// draws the route on the map
	class RouteOverlay extends Overlay {
		
		GeoPoint start;
		GeoPoint end;
		
		public RouteOverlay(GeoPoint s, GeoPoint e) {
			start = s;
			end = e;
		}
			
		public void draw(Canvas canvas, MapView mapv, boolean shadow) {
			// set up draw configuration
			
			
			super.draw(canvas, mapv, shadow);
			Paint mPaint = new Paint();
			mPaint.setDither(true);
			mPaint.setColor(Color.BLUE);
			mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
			mPaint.setStrokeJoin(Paint.Join.ROUND);
			mPaint.setStrokeCap(Paint.Cap.ROUND);
			mPaint.setStrokeWidth(5);
			
			// holds the coordinates that draws the line
			ArrayList<GeoPoint> shapePoints = aMapItem.getShapePoints();
			
			// points and path to draw the line.
			Point p1 = new Point();
			Point p2 = new Point();
			Path path = new Path();
			
			// draw out the route on the display
//			for(int i = 0; i < shapePoints.size() - 1; i++) {
//				projection.toPixels(shapePoints.get(i), p1);
//				projection.toPixels(shapePoints.get(i+1), p2);
				
				projection.toPixels(start, p1);
				projection.toPixels(end, p2);
				
				path.moveTo(p2.x, p2.y);
				path.lineTo(p1.x, p1.y);
				
				canvas.drawPath(path,mPaint);
			//}
		}
	}

	
	/**
	 * Starts a new thread for going through the cursor 
	 * and populating the list with items 
	 * This method is used to spawn a new hidden 
	 * thread witch calls the runWork method
	 */
	public void start()
		{
			Runnable r = new Runnable()
				{
					public void run()
						{
							runWork();
						}

				
				};
			Thread t = new Thread(r);
			t.start();
		}
	
	private void runWork() {
		db = new SQLiteOperationsWrapper(this);
		db.open();
		
		aMapItem = db.getMapPoints(shapeID);
		
		if(aMapItem == null) {
			System.out.println("aMapItem was null");
			
			String base = new BaseServicesURL().getMapURL();
		
			// the URL get URL for the shapePts
			//added this to check for errors while trying to 
			//get data via HTTPGET
			String data = JSONBusStopHTTPGet.readBusStopJSONFeed(base + shapeID,this.getIntent());
			if(this.getIntent().getExtras().getBoolean("failedGetRequest")){
				
				System.out.println("Failed to http get");
				runOnUiThread(new Runnable() {   
					public void run(){  
				Toast.makeText(ct, "There was an error, Please check your data connection", Toast.LENGTH_LONG).show();
					} 
				});
				Intent intent2 = new Intent(this ,MainMenuActivity.class);
				startActivity(intent2);
				finish();
				db.close();
				return;
			}else{
			// parse the return data into a usable MapItem
			aMapItem = ShapeParser.parse(data, shapeID);
			
			db.insertShapeRow(aMapItem);
			}
		}
		
		// close the database
		db.close();
		
		// determine the number of points in the sequence
		int shPtSize = aMapItem.getShapePoints().size();
		
		// determine the center point to be used when displaying the map
		GeoPoint start = aMapItem.getShapePoints().get(0);
		GeoPoint end = aMapItem.getShapePoints().get(shPtSize - 1);
		
		int centerLat = (start.getLatitudeE6() + end.getLatitudeE6())/2;
		int centerLon = (start.getLongitudeE6() + end.getLongitudeE6())/2;
				
		center = new GeoPoint(centerLat, centerLon);
		
		// set center of the map
		map.getController().setCenter(center);
		
		
		ArrayList<GeoPoint> shapePoints = aMapItem.getShapePoints();
		
		for(int i = 0; i < shapePoints.size() - 1; i++) {
			mapOverlays.add(new RouteOverlay(shapePoints.get(i), shapePoints.get(i+1)));
		}
		runOnUiThread(new Runnable() {   
			public void run(){  
		progess.setVisibility(View.GONE);
		txtLoading.setVisibility(View.GONE); 
		rl.setVisibility(View.VISIBLE);  
			} }); 
	}
	
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	        
	    	// MapView object that holds the map
			map = (MapView) findViewById(R.id.map);
			// Configure the Map
			map.setBuiltInZoomControls(true);
			map.setSatellite(false);
			
	        List<Overlay> mapOverlays = map.getOverlays(); 
	        
	        Drawable drawable = this.getResources().getDrawable(R.drawable.next_bus_pin_small);
	        myPointOverlay = new PointOverlay(drawable, this); 
	        
	     		
	     	center  = new GeoPoint((int) (getIntent().getExtras().getInt(ViewStopsActivity.STOP_LAT_KEY)),
	     						   (int) (getIntent().getExtras().getInt(ViewStopsActivity.STOP_LONG_KEY)));
	     		
	        OverlayItem overlayitem = new OverlayItem(center, "Hello", "!"); 
	     		
	        
	        myPointOverlay.addOverlay(overlayitem);
	        mapOverlays.add(myPointOverlay);
	             
			MapController mapController = map.getController();
			mapController.animateTo(center);
			mapController.setCenter(center);

			mapController.setZoom(19);
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	
	public void onPause(){
		super.onPause();
		
		// set center of the map
	//	map.getController().animateTo(center);
		//map.getController().setZoom(19);
		
	}
}
